package a66weding.com.jiehuntong.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.MarriageProposalBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.UpLoadImage;
import a66weding.com.jiehuntong.common.MessageEvent;
import a66weding.com.jiehuntong.common.api.Url;
import a66weding.com.jiehuntong.common.utils.FileUtil;
import a66weding.com.jiehuntong.common.utils.TimeUtils;
import a66weding.com.jiehuntong.common.utils.dataselect.DataSelectUtil;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;
import a66weding.com.jiehuntong.inner.DataCallBack;
import a66weding.com.jiehuntong.pager.IContant;
import a66weding.com.jiehuntong.widgets.CircularImage;
import a66weding.com.jiehuntong.widgets.dialog.prompt.SimpleHUD;

import static a66weding.com.jiehuntong.common.utils.CUtils.showToast;

/**
 * Created by admin on 2016/7/11.
 * 点击某个任务的编辑进入的界面;
 */
public class JobDetail_Edit_Activity extends Activity implements View.OnClickListener ,IContant,OnNetResultListener,DataCallBack{
    public static final int NONE = 0;
    public static final int PHOTOHRAPH = 1;// 拍照
    public static final int PHOTOZOOM = 2; // 缩放
    public static final int PHOTORESOULT = 3;// 结果

    public static final String IMAGE_UNSPECIFIED = "image/*";
    public  static int MONEY_RECODE = 4;
    private CircularImage circularImage;
    private Button photoBtn, cameraBtn, quxiaoBtn;
    //头像
    //主要帮手
    private TextView main_help_tv_name;
    //点击制定时间
    private TextView engagement_date;
    //点击提醒时间
    private TextView reminder_date;
    private RelativeLayout engagement_date_R;
    private RelativeLayout reminder_date_R;
    //接受的时间的字符串
    private String time;
    //设置地点
    private TextView location_place;
    private String place;
    //金额
    private RelativeLayout consumption_expected;
    private String money;
    private TextView consumption_expected_money;
    //点击是否完成此项任务
    private ImageView is_completion_image;
    private boolean flag = true;
    //标题
    private String title;
    //注意事项
    private RelativeLayout precautions;
    //注意事项要显示的内容
    private TextView tv;
    //请输入备注点击备注
    private RelativeLayout precautions_content;
    private MarriageProposalBean.DataBean dataBean;
    //金额
    //备注
    private RelativeLayout remark;
    //备注的内容
    private TextView content_tv;
    //主要帮友
    //主要参与人员
    private RelativeLayout participants;
    private TextView participants_tv_name;
    //本流程图片的名称
    private String HEADName;
    private Bitmap headBitmap;
    private RelativeLayout location;
    private RelativeLayout main_help_Relative;
    //上传头像;
    private  RelativeLayout upload_avatar;
    private TextView title_tv;
    private static final int PERMISSION_CAMERA=5;
    private static final int PERMISSION_SDCARD = 4;
    private static final int TAKE_PHOTO=2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_task);
        Intent intent = getIntent();
        dataBean = (MarriageProposalBean.DataBean) intent.getSerializableExtra(JobDetail.TASK_FLAG);
        title = dataBean.getBookTitle();
         EventBus.getDefault().register(this);
        initView();
        initData(dataBean);
    }

    private void initView() {
        title_tv = (TextView) findViewById(R.id.title_tv);
        circularImage = (CircularImage) findViewById(R.id.cover_user_photo1);
        /**
         *  photoBtn = (Button) view.findViewById(R.id.dialog_photo_button);
         cameraBtn = (Button) view.findViewById(R.id.dialog_camera_button);
         quxiaoBtn = (Button) view.findViewById(R.id.dialog_quxiao_button);
         */
        main_help_tv_name = (TextView) findViewById(R.id.main_help_tv_name);
        engagement_date = (TextView) findViewById(R.id.engagement_date_iamge_time);
        reminder_date = (TextView) findViewById(R.id.reminder_date_tv);
        location_place = (TextView) findViewById(R.id.location_place);
        consumption_expected = (RelativeLayout) findViewById(R.id.consumption_expected);
        consumption_expected.setOnClickListener(this);
        consumption_expected_money = (TextView) findViewById(R.id.consumption_expected_money);
        is_completion_image = (ImageView) findViewById(R.id.is_completion_plan_image);
        is_completion_image.setOnClickListener(this);
        title_tv = (TextView) findViewById(R.id.title_tv);
        //点击注意事项;
        precautions = (RelativeLayout) findViewById(R.id.precautions);
        precautions.setOnClickListener(this);
        engagement_date_R = (RelativeLayout) findViewById(R.id.engagement_date);
        engagement_date_R.setOnClickListener(this);
        reminder_date_R = (RelativeLayout) findViewById(R.id.reminder_date);
        reminder_date_R.setOnClickListener(this);
        //显示的内容;
        tv = (TextView) findViewById(R.id.precautions_content_tv);
        //点击的备注;
        remark = (RelativeLayout) findViewById(R.id.Remark);
        remark.setOnClickListener(this);
        content_tv = (TextView) findViewById(R.id.remark_tv);
        //主要参与
        upload_avatar = (RelativeLayout) findViewById(R.id.upload_avatar);
        upload_avatar.setOnClickListener(this);
        participants = (RelativeLayout) findViewById(R.id.participants);
        main_help_Relative  = (RelativeLayout) findViewById(R.id.main_help_Relative);
        main_help_Relative.setOnClickListener(this);
        participants.setOnClickListener(this);
        participants_tv_name = (TextView) findViewById(R.id.participants_tv_name);
        location = (RelativeLayout) findViewById(R.id.location);
        location.setOnClickListener(this);

    }


    private void initData(MarriageProposalBean.DataBean dataBean){
        title_tv.setText(dataBean.getBookTitle());
        HEADName = dataBean.getWeddingBookID()+".jpg";
        headBitmap = FileUtil.getBitmapFromDisk(HEADName,this);
        //判断
        if(headBitmap!=null){
            circularImage.setImageBitmap(headBitmap);
        }
        location_place.setText(dataBean.getBookPlace()!=null?dataBean.getBookPlace():"");
        consumption_expected_money.setText(dataBean.getBudgetMoney()!=0?""+dataBean.getBudgetMoney():"");
        //显示提示内容;
        tv.setText(dataBean.getNotice());
        //判断是否完成了任务
        if(dataBean.isIsComplete()){
            is_completion_image.setImageResource(R.mipmap.switch_button_selector);
        }else{
            is_completion_image.setImageResource(R.mipmap.switch_button_normal);
        }
        String content = dataBean.getRemarks();
        if(content==null||"".equals(content)){

        }else{
            content_tv.setText(content);
        }
        //主要参与的朋友
        participants_tv_name.setText(dataBean.getParticipant()==null?"":dataBean.getParticipant());
        //主要帮友
        main_help_tv_name.setText(dataBean.getNvc_Name());
        //计划时间
        if (dataBean.getBookDate()!=null){
            engagement_date.setText(dataBean.getBookDate());
        }
       //提醒时间;
        if (dataBean.getRemindDate()!=null){
            reminder_date.setText(dataBean.getRemindDate());
        }
        tv.setText(R.string.zhuyishixiang);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.upload_avatar:
                uploadAvatar();
                break;

            /**
             *  主要帮手
             */
            case R.id.main_help_Relative:
                //如果好友列表主要帮手有id 我们就不能跳转到主要帮手的界面
                if ("".equals(engagement_date.getText())){
                    SimpleHUD.showErrorMessage(this,"请输入任务时间");
                }else {
                    if (dataBean.getAssistantID() == 0) {
                        Intent intent_mainhelp = new Intent(this, MainHelpActivity1.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(JobDetail.TASK_FLAG, dataBean);
                        intent_mainhelp.putExtras(bundle);
                        startActivityForResult(intent_mainhelp, 7);
                    }
                }
                break;
            //点击制定时间
            case R.id.engagement_date:
                DataSelectUtil.getInstance().showdatePopupWindow(v,this,this,1);
                break;
            case R.id.reminder_date:
                DataSelectUtil.getInstance().showdatePopupWindow(v,this,this,2);
                break;
            //点击设置地点
            case R.id.location:
//                Intent localintent = new Intent(this,LocalActivity.class);
//                localintent.putExtra(JobDetail.TASK_FLAG,title);
//                localintent.putExtra("place",location_place.getText());
//                startActivity(localintent);
                GoToLocal();
                break;
            /**
             * 预计消费金额;
             */
            case R.id.consumption_expected:
                Intent moneyIntent = new Intent(this,MoneyActivity.class);
                moneyIntent.putExtra(JobDetail.TASK_FLAG,title);
                moneyIntent.putExtra("money",consumption_expected_money.getText());
                startActivityForResult(moneyIntent,MONEY_RECODE);
                break;

            case R.id.is_completion_plan_image:
                //防止连击;
               if (!TimeUtils.isFastDoubleClick()) {
                   //如果为true
                   if (flag) {
                       is_completion_image.setImageResource(R.mipmap.switch_button_selector);
                       sendIsDone(flag);
                       flag = false;

                   } else {
                       is_completion_image.setImageResource(R.mipmap.switch_button_normal);
                       sendIsDone(flag);
                       flag = true;
                   }
                   //进行网络请求
               }
                break;
            case  R.id. precautions:
                //

                break;
            /**
             * 备注 case
             */
            case R.id.Remark:
                Intent remarkIntent = new Intent(this,NoticeActivity.class);
                Bundle bundle1 = new Bundle();
                bundle1.putSerializable(JobDetail.TASK_FLAG,dataBean);
                remarkIntent.putExtras(bundle1);
                startActivityForResult(remarkIntent,6);
                break;

            /**
             *   点击主要参与人员
             */
            case R.id.participants:
                Intent intent_participants = new Intent(this,ParticipantsActivity.class);
                intent_participants.putExtra(JobDetail.TASK_FLAG,dataBean);
                startActivityForResult(intent_participants,8);
                break;
        }
    }

    /**
     * POST Wedding/Update_IsComplete?Token={Token}&i_Id={i_Id}
     修改流程是否完成
     * @param flag
     */
    private void sendIsDone(boolean flag){
        dataBean.setIsComplete(flag);
        String useUrl= UrlDealUtil.getRealUrl(RequestCode.UPDATE_ISCOMPLETE);
        HashMap<String,String> paramsMap=new HashMap<>();
        paramsMap.put("BookTitle",title);
        if(flag){
            paramsMap.put("IsComplete",""+1);
        }else{
            paramsMap.put("IsComplete",""+0);
        }
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST,useUrl, this, CommonResultBean.class, RequestCode.UPDATE_ISCOMPLETE, paramsMap);
        HttpHandleUtil.executeCommonPost(this,httpRequestBean);

    }

    private void uploadAvatar(){
        View view = getLayoutInflater().inflate(R.layout.activity_tools_dialog_photo, null);
        photoBtn = (Button) view.findViewById(R.id.dialog_photo_button);
        cameraBtn = (Button) view.findViewById(R.id.dialog_camera_button);
        quxiaoBtn = (Button) view.findViewById(R.id.dialog_quxiao_button);

        photoBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                showPhoto();
                dialog.dismiss();
            }
        });
        cameraBtn.setOnClickListener(new View.OnClickListener() {
           @Override
            public void onClick(View v) {
                showCamera();
                dialog.dismiss();
            }

        });
        quxiaoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog = new Dialog(this, R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        // 设置显示动画
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        dialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }
    private String ImageName;
    /**
     * 拍照
     */
    public void showCamera() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //申请MOUNT_UNMOUNT_FILESYSTEMS权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_CAMERA);
        }else{
            ImageName = "/" + getStringToday() + ".jpg";
            // 调用系统的拍照功能
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
                    Environment.getExternalStorageDirectory(), ImageName)));
            startActivityForResult(intent, PHOTOHRAPH);
        }
    }

    /**
     * 给图片命名
     * @return
     */
    public static String getStringToday() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }


    /**
     * 系统图库
     */
    private void showPhoto() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]
                    {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SDCARD);
        } else {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                IMAGE_UNSPECIFIED);

        // 调用剪切功能
        startActivityForResult(intent, PHOTOZOOM);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doNext(requestCode, grantResults);
    }

    private void doNext(int requestCode, int[] grantResults) {
        if (requestCode == PERMISSION_CAMERA) {
            if (grantResults.length>0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                ImageName = "/" + getStringToday() + ".jpg";
                // 调用系统的拍照功能
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
                        Environment.getExternalStorageDirectory(), ImageName)));
                startActivityForResult(intent, PHOTOHRAPH);
            } else {
                showToast("请打开手机拍照权限后在操作");
            }
        }else if(requestCode ==PERMISSION_SDCARD){
            if(grantResults.length>0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        IMAGE_UNSPECIFIED);
                // 调用剪切功能
                startActivityForResult(intent, PHOTOZOOM);
            }else{
                showToast("请打开手机SD卡权限后在操作");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == NONE)
            return;
        // 拍照
        if (requestCode == PHOTOHRAPH) {
            // 设置文件保存路径这里放在跟目录下
            File picture = new File(Environment.getExternalStorageDirectory()
                    +ImageName);
            startPhotoZoom(Uri.fromFile(picture));

        }
        if (data == null)
            return;

        // 读取相册缩放图片
        if (requestCode == PHOTOZOOM) {
            startPhotoZoom(data.getData());
        }
        // 处理结果
        if (requestCode == PHOTORESOULT) {
            if (data!=null){
                setPicToView(data);
            }

        }
        switch (requestCode) {

            case 4:
                String money = data.getStringExtra(MONEY);
                consumption_expected_money.setText(money);
                int b;
                if("".equals(money)){
                  b = 0;
                }else{
                    if(money.length() > 12) {
                        Toast.makeText(JobDetail_Edit_Activity.this,"对不起,输入的金额过大,请重新输入",Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        b = Integer.parseInt(money);
                    }
                }
                dataBean.setBudgetMoney((double) b);
                break;
            case 6:
              dataBean = (MarriageProposalBean.DataBean) data.getSerializableExtra(JobDetail.TASK_FLAG);
                initData(dataBean);
                break;
            case  7:
                dataBean = (MarriageProposalBean.DataBean) data.getSerializableExtra(MainHelpActivity1.MAIN_HELP_NAME);
                initData(dataBean);
                break;
            case 8:
                dataBean = (MarriageProposalBean.DataBean) data.getSerializableExtra(JobDetail.TASK_FLAG);
                initData(dataBean);
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * POST WeddingMobileApiSD/PostUpBookPicture?Token={Token}&mobileStr={mobileStr}&bookId={bookId}
     */
    private void uploadfile(final File saveFile) {
        //图片上传地址
        String phone = DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_MobilePhone();
        final String url = Url.SURL + "/WeddingMobileApiSD/PostUpBookPicture?Token=00&mobileStr="+phone+"&bookId=" + dataBean.getWeddingBookID();
        new Thread() {
            @Override
            public void run() {
                String result = uploadFile(saveFile, url);
                Gson mgson = new Gson();
                UpLoadImage upLoadImage = mgson.fromJson(result,UpLoadImage.class);
                dataBean.setPicture(upLoadImage.getResult().getUrlField());
                //将头像的url 地址封装到数据库中
            }
        }.start();
    }

        /** * android上传文件到服务器
         * @param file 需要上传的文件
         * @param RequestURL 请求的rul
         * @return 返回响应的内容
         */
        public  String uploadFile(File file,String RequestURL) {
            String result="";
            String BOUNDARY = UUID.randomUUID().toString();
            //边界标识 随机生成
            String PREFIX = "--" , LINE_END = "\r\n";
            String CONTENT_TYPE = "multipart/form-data"; //内容类型
            try {
                URL url = new URL(RequestURL);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10*100000); conn.setConnectTimeout(10*100000);
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setUseCaches(false);
                conn.setRequestMethod("POST"); //请求方式
                conn.setRequestProperty("Charset", "utf-8");
                //设置编码
                conn.setRequestProperty("connection", "keep-alive");
                conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
                if(file!=null) {
                    /** * 当文件不为空，把文件包装并且上传 */
                    OutputStream outputSteam=conn.getOutputStream();
                    DataOutputStream dos = new DataOutputStream(outputSteam);
                    StringBuffer sb = new StringBuffer();
                    sb.append(PREFIX);
                    sb.append(BOUNDARY);
                    sb.append(LINE_END);
                    sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END);
                    sb.append("Content-Type: application/octet-stream; charset=utf-8"+LINE_END);
                    sb.append(LINE_END);
                    dos.write(sb.toString().getBytes());
                    InputStream is = new FileInputStream(file);
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    while((len=is.read(bytes))!=-1)
                    {
                        dos.write(bytes, 0, len);
                    }
                    is.close();
                    dos.write(LINE_END.getBytes());
                    byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
                    dos.write(end_data);
                    dos.flush();
                    /**
                     * 获取响应码 200=成功
                     * 当响应成功，获取响应的流
                     */
                    int res = conn.getResponseCode();
                    if(res==200)
                    {
                        // 读取返回数据
                        StringBuffer strBuf = new StringBuffer();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        String line = null;
                        while ((line = reader.readLine()) != null) {
                            strBuf.append(line).append("\n");
                        }
                       result = strBuf.toString();
                        reader.close();
                        return result;
                    }
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }


    /**
     * 保存裁剪之后的图片数据
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(photo);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            File saveFile=new File(FileUtil.getImgFile(this),HEADName);
            uploadfile(saveFile);
            try {
                FileOutputStream fileOutputStream = new FileOutputStream(saveFile);
                fileOutputStream.write(byteArray,0,byteArray.length);
                fileOutputStream.flush();
                fileOutputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            circularImage.setImageDrawable(drawable);
        }
    }
    //返回
    public void back(View view){
            Intent intent  = new Intent();
            intent.putExtra(JobDetail.TASK_FLAG,dataBean);
            setResult(1,intent);
            this.finish();
          overridePendingTransition(R.anim.back_enter, R.anim.back_exit);
    }

    @Subscribe
    public void onEvent(MessageEvent event){
        place = event.getPlace();
        location_place.setText(place);
        dataBean.setBookPlace(place);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 裁剪图片;
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 64);
        intent.putExtra("outputY", 64);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTORESOULT);
    }

            //展示的对话框
    public Dialog dialog;


    private CommonResultBean been;
    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if(data instanceof  CommonResultBean){
            been = (CommonResultBean) data;
            switch (been.getResCode()){
                case "0000":
                    showToast("修改成功了");
                    break;
            }
        }
    }

    @Override
    public void onError(ErrorBean errorBean) {

    }

    @Override
    public void sendData(String time, int flag) {
        if (flag ==1){
            engagement_date.setText(time);
            dataBean.setBookDate(time);
            //任务时间
            String useUrl = UrlDealUtil.getRealUrl( RequestCode.UPDATE_PROCESS);
            //参数;
            HashMap<String,String> paramsMap=new HashMap<>();
            paramsMap.put("BookDate",time);
            paramsMap.put("BookTitle",title);
            HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, useUrl,JobDetail_Edit_Activity.this, CommonResultBean.class,  RequestCode.UPDATE_PROCESS, paramsMap);
            HttpHandleUtil.executeCommonPost(JobDetail_Edit_Activity.this,httpRequestBean);
        }else if (flag==2){
            reminder_date.setText(time);
            dataBean.setRemindDate(time);
            //任务时间
            String useUrl = UrlDealUtil.getRealUrl( RequestCode.UPDATE_REMINDDATE);
            //参数;
            HashMap<String,String> paramsMap=new HashMap<>();
            paramsMap.put("RemindDate",time);
            paramsMap.put("BookTitle",title);
            HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, useUrl,JobDetail_Edit_Activity.this, CommonResultBean.class,  RequestCode.UPDATE_REMINDDATE, paramsMap);
            HttpHandleUtil.executeCommonPost(JobDetail_Edit_Activity.this,httpRequestBean);
        }
    }


    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra(JobDetail.TASK_FLAG,dataBean);
            setResult(1,intent);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    private void GoToLocal(){
        Intent intent = new Intent(this,LocalActivity1.class);
        intent.putExtra(JobDetail.TASK_FLAG,dataBean);
        startActivityForResult(intent,8);
    }


}
